package network.impl;

import java.net.UnknownHostException;

import network.IClientNetwork;
import model.INetworkModel;
import model.impl.ModelListener;
import sharedNetwork.Connection;
import sharedNetwork.NetworkFlags;


public class Network implements IClientNetwork, ModelListener, ClientInputThreadListener {
	
	private NetClient netClient;
	private INetworkModel model;
	private ClientNetworkListener listener;
	private boolean isConnected;
	
	private Network(ClientNetworkListener listener, INetworkModel model) {
		this.model = model;
		model.addModelListener(this);
		this.listener = listener;
		isConnected = false;
	}
	
	public static IClientNetwork newNetwork(ClientNetworkListener listener, INetworkModel model) {
		return new Network(listener, model);
	}
	
	private void connect() throws ConnectionFailedException, UnknownHostException {
		netClient = new NetClient(model.getServerAddress(), 6701);
		netClient.connect();
		netClient.addNetworkListener(listener);
		netClient.addClientInputThreadListener(this);
	}

	@Override
	public void modelChanged() {
		if (isConnected) {
			Object obj = model.getData();
			netClient.send(obj);
		} else {
			Connection connection = model.getConnection();
			if (connection != null) {
				try {
					connect();
					netClient.send(connection);
					isConnected = true;
				} catch (ConnectionFailedException e) {
					listener.connectionFailed();
				} catch (UnknownHostException e) {
					listener.serverAddressNotFound();
				}
			}
		}
	}

	@Override
	public void connectionLost() {
		netClient.shutDown();
		isConnected = false;
	}

	@Override
	public void disconnect() {
		netClient.send(NetworkFlags.DISCONNECTION_ACCEPTED);
		netClient.shutDown();
		isConnected = false;
		System.out.println("Diconnecting the client");
	}

	@Override
	public void disconnectionAccepted() {
		netClient.shutDown();
		isConnected = false;
		System.out.println("Disconnected from the server");
	}
}
